universal-stores
State management made simple.
Stores are a simple yet powerful way to manage an application
state. Some examples of stores can be found in Svelte (e.g. writable, readable) and Solid.js (e.g. createSignal).
This package provides a framework-agnostic implementation of this concept.
NPM Package
npm install universal-stores
Documentation
Store
In a nutshell, stores are observable containers of values.
A Store<T>
is an object that provides the following methods:
subscribe(subscriber)
, to attach subscribers;set(value)
, to update the current value of the store and send it to all subscribers;update(updater)
, to update the value using a function that takes the current one as an argument.
There is also a getter value
that retrieves the current value of the store:
import {makeStore} from 'universal-stores';
const store$ = makeStore(0);
console.log(store$.value);
store$.set(1);
console.log(store$.value);
When a subscriber is attached to a store it immediately receives the current value.
Every time the value of the store changes (by using set
or update
) all subscribers get the new value.
Store<T>
also contains a getter (nOfSubscriptions
) that lets you know how many subscriptions
are active at a given moment (this could be useful if you are trying to optimize your code).
Let's see an example:
import {makeStore} from 'universal-stores';
const store$ = makeStore(0);
console.log(store$.value);
const unsubscribe = store$.subscribe((v) => console.log(v));
store$.set(1);
unsubscribe();
store$.set(2);
store$.subscribe((v) => console.log(v));
Let's see an example that uses the update method:
import {makeStore} from 'universal-stores';
const store$ = makeStore(0);
store$.subscribe((v) => console.log(v));
const plusOne = (n: number) => n + 1;
store$.update(plusOne);
store$.update(plusOne);
store$.update(plusOne);
A nice feature of Store<T>
is that it deduplicates subscribers,
that is you can't accidentally add the same subscriber more than
once to the same store (just like the DOM addEventListener method), although
every time you add it, it will receive the current value:
import {makeStore} from 'universal-stores';
const store$ = makeStore(0);
const subscriber = (v: number) => console.log(v);
const unsubscribe1 = store$.subscribe(subscriber);
const unsubscribe2 = store$.subscribe(subscriber);
const unsubscribe3 = store$.subscribe(subscriber);
console.log(store$.nOfSubscriptions);
unsubscribe3();
unsubscribe2();
unsubscribe1();
console.log(store$.nOfSubscriptions);
If you ever needed to add the same function
more than once you can still achieve that by simply wrapping it inside an arrow function:
import {makeStore} from 'universal-stores';
const store$ = makeStore(0);
const subscriber = (v: number) => console.log(v);
console.log(store$.nOfSubscriptions);
const unsubscribe1 = store$.subscribe(subscriber);
console.log(store$.nOfSubscriptions);
const unsubscribe2 = store$.subscribe((v) => subscriber(v));
console.log(store$.nOfSubscriptions);
unsubscribe2();
console.log(store$.nOfSubscriptions);
unsubscribe1();
console.log(store$.nOfSubscriptions);
Deriving
A derived store is a ReadonlyStore<T>
(see below) whose
value is the result of a computation on one or more
source stores.
Example:
import {makeStore, makeDerivedStore} from 'universal-stores';
const store$ = makeStore(1);
const derived$ = makeDerivedStore(store$, (n) => n + 100);
derived$.subscribe((v) => console.log(v));
store$.set(3);
Example with multiple sources:
import {makeStore, makeDerivedStore} from 'universal-stores';
const firstWord$ = makeStore('hello');
const secondWord$ = makeStore('world!');
const derived$ = makeDerivedStore([firstWord$, secondWord$], ([first, second]) => `${first} ${second}`);
derived$.subscribe((v) => console.log(v));
firstWord$.set('hi');
ReadonlyStore
When you derive a store, you get back a ReadonlyStore<T>
.
This type lacks the set
and update
methods.
A Store<T>
is in fact an extension of a ReadonlyStore<T>
that adds the aforementioned methods.
As a rule of thumb, it is preferable to pass around ReadonlyStore<T>
s,
to better encapsulate your state and prevent unwanted set
s or update
s.
Lazy loading
To create a Store<T>
or a ReadonlyStore<T>
you can use makeStore(...)
or makeReadonlyStore(...)
.
Both these functions take an optional initial value as their first parameter, and
that's their most common use case, but sometimes it could be useful
to lazy load a store or alter its value by using a StartHandler
.
A StartHandler
is a function that gets called whenever the store is activated,
i.e. it gets at least one subscription. If the StartHandler
returns a function,
that function will be called whenever the store is deactivated, i.e.
it has no active subscriptions.
Example:
import {makeReadonlyStore} from 'universal-stores';
const oneHertzPulse$ = makeReadonlyStore<number>(undefined, (set) => {
console.log('start');
const interval = setInterval(() => {
set(performance.now());
}, 1000);
return () => {
console.log('cleanup');
clearInterval(interval);
};
});
const unsubscribe = oneHertzPulse$.subscribe((time) => console.log(time));
setTimeout(() => {
unsubscribe();
}, 5000);
Optimizing notifications to subscribers
makeStore
can also take a configuration object as its second
argument. The configuration can contain a StartHandler
and an EqualityComparator
.
An EqualityComparator
is a comparing function that takes two arguments: the current value
of the store and the value that's being set (either by a call to store$.set
or store$.update
).
If the two values are equal (i.e. the function returns true), the store value remains the same
and the subscribers won't be notified.
By default makeStore
uses a simple lambda that checks for equality with the strict equality operator, i.e. (a, b) => a === b
.
If you use objects in your stores you might consider passing a custom function that performs
a deep equality check, taking into account the tradeoff between having to perform a more expensive comparison vs unnecessarily notifing lots of subscribers.
Similarly, makeDerivedStore
can also take a configuration object with a custom comparator as its third argument.
Example:
import {makeStore} from 'universal-stores';
const objectStore$ = makeStore(
{veryLongText: '...', hash: 0xffaa},
{
comparator: (a, b) => a.hash === b.hash,
},
);
objectStore$.set({veryLongText: '...', hash: 0xbbdd});
objectStore$.set({veryLongText: '...', hash: 0xbbdd});
Example with derived:
import {makeStore, makeDerivedStore} from 'universal-stores';
const objectStore$ = makeStore({veryLongText: '...', hash: 0xffaa});
const derivedObjectStore$ = makeDerivedStore(objectStore$, (x) => x, {
comparator: (a, b) => a.hash === b.hash,
});
objectStore$.set({veryLongText: '...', hash: 0xbbdd});
objectStore$.set({veryLongText: '...', hash: 0xbbdd});
Motivation
UI frameworks often ship with their own state management layer,
either built-in or provided by third parties.
State management, however, should not be coupled to
the UI framework or library you're currently working with. Moreover, state management
is also useful in non-UI applications (e.g. backend, background processes, etc.).
universal-stores is a standalone and lightweight state management library whose only concern
is providing primitives for storing and observing state. These primitives can then
be used as building blocks for libraries
and applications of any kind, decoupled from
the presentation layer until the very moment
you need to show data to the user.
Ecosystem
For a complete list of packages that use universal-stores you can look at the dependents tab on npm.
Adapters